/**
 * 产品新建页面交互逻辑
 */
import { createDataItem } from '../../js/api.js';

/**
 * 初始化图片预览功能
 */
function initImagePreview() {
    const imageInput = document.getElementById('image');
    const previewImage = document.getElementById('imagePreview');

    imageInput.addEventListener('change', (e) => {
        const file = e.target.files[0];
        if (file) {
            const reader = new FileReader();
            reader.onload = (event) => {
                previewImage.src = event.target.result;
                previewImage.style.display = 'block';
            };
            reader.readAsDataURL(file);
        } else {
            previewImage.src = '';
            previewImage.style.display = 'none';
        }
    });
}

/**
 * 初始化表单提交事件监听
 */
function initFormSubmit() {
    const createForm = document.getElementById('createForm');
    createForm.addEventListener('submit', async (e) => {
        e.preventDefault();

        // 获取表单数据
        const formData = new FormData();
        formData.append('name', document.getElementById('name').value.trim());
        formData.append('category_id', parseInt(document.getElementById('categoryId').value));
        formData.append('price', parseFloat(document.getElementById('price').value));
        formData.append('description', document.getElementById('description').value.trim());
        formData.append('is_on_sale', document.getElementById('isOnSale').value === 'true');

        // 添加图片文件（如果有）
        const imageFile = document.getElementById('image').files[0];
        if (imageFile) {
            formData.append('image', imageFile);
        }

        // 简单表单验证
        if (!formData.get('name')) {
            alert('请输入产品名称');
            return;
        }

        if (isNaN(formData.get('category_id'))) {
            alert('请输入有效的分类ID');
            return;
        }

        if (isNaN(formData.get('price')) || formData.get('price') < 0) {
            alert('请输入有效的价格');
            return;
        }

        try {
            // 调用API创建产品
            const success = await createDataItem(formData);
            if (success) {
                alert('产品创建成功！');
                window.location.href = 'list.html'; // 跳转到列表页
            }
        } catch (error) {
            console.error('创建产品失败:', error);
            alert('创建产品失败: ' + (error.message || '未知错误'));
        }
    });
}

// 页面加载完成后初始化
window.addEventListener('DOMContentLoaded', () => {
    initImagePreview();
    initFormSubmit();
});